package parser

import (
	"gravure/src/lexer"
	"strings"
)

type NodeType int

const (
	NodeDocument NodeType = iota
	NodeHeading
	NodeParagraph
	nodeList
	NodeListItem
	NodeCodeBlock
	NodeText
	NodeBold
	NodeItalic
	NodeLink
	NodeImage
	NodeHorizontalRule
)

type Node struct {
	Type     NodeType
	Content  string
	Children []*Node
	Level    int //用于标题级别
	URL      string
}

type Parser struct {
	lex          *lexer.Lexer
	currentToken lexer.Token
	nextToken    lexer.Token
}

func NewParser(lex *lexer.Lexer) *Parser {
	p := &Parser{lex: lex}
	p.currentToken = p.lex.NextToken()
	p.nextToken = p.lex.NextToken()
	return p
}
func (p *Parser) Parser() *Node {
	document := &Node{Type: NodeDocument, Children: []*Node{}}

	for p.currentToken.Type != lexer.TokenEOF {
		switch p.currentToken.Type {
		case lexer.TokenHeading:
			document.Children = append(document.Children, p.parseHeading())
		}
	}
	return document
}

func (p *Parser) parseHeading() *Node {
	content := p.currentToken.Content
	level := strings.Count(content, "#")
	if level > 6 {
		level = level - 1
	}
	content = strings.TrimSpace(content[level:])
	node := &Node{
		Type:    NodeHeading,
		Content: content,
		Level:   level,
	}
	p.eat(lexer.TokenHeading)
	return node
}

func (p *Parser) eat() {
	p.currentToken = p.nextToken
	if p.currentToken.Type != lexer.TokenEOF {
		p.nextToken = p.lex.NextToken()
	}
}
